<template>
  <el-card class="container">
    <div slot="header">
      <el-button type="primary" @click="showDialog" class="el-icon-plus"
        >添加</el-button
      >
    </div>
    <el-table
    class="card container"
      :data="trademarkList"
      border
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column label="序号" width="180" type="index"> </el-table-column>
      <el-table-column prop="tmName" label="品牌名称"> </el-table-column>
      <el-table-column label="品牌LOGO" prop="logoUrl">
        <!-- 
          照片不能显示，需要作用域插槽，给当前列传递数据
          slotScoped.$index 下标
          slotScoped.row 当前行数据
         -->
        <template v-slot="{ row }">
          <img :src="row.logoUrl" alt="品牌LOGO" class="logoImg" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="{ row }">
          <el-button
            type="warning"
            icon="el-icon-edit"
            @click="updateTrademark(row)"
          >
            修改</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            @click="delTrademark(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[3, 6, 9, 12]"
      :page-size="100"
      layout="prev, pager, next, jumper,total,sizes"
      :total="total"
    >
    </el-pagination>
    <!-- 添加品牌 -->
    <el-dialog
      :title="`${isAddOrUpdate ? '添加' : '修改'}品牌`"
      :visible.sync="visible"
      width="30%"
    >
      <el-form :model="trademark" ref="form" :rules="rules">
        <el-form-item label="品牌名称" prop="tmName" label-width="100px">
          <el-input v-model="trademark.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <!--
            rules ,起的名字必须和收集起来的名字一样要用prop
            图片上传组件
             action 上传的服务器地址 
               action="http://39.98.123.211/admin/product/fileUpload"
                action="/dev-api/admin/product/fileUpload" 走代理服务器，转发目标服务器
                :action="`${process.env.VUE_APP_BASE_API}/admin/product/fileUpload`"
                     ${process.env.VUE_APP_BASE_API},这样写会得不到，vue只会从this上找，需要保存在this上
              show-file-list 是否可以上传多张照片
              on-success 上传成功的触发回调
              before-upload 上传之前触发的回调
                限制图片的大小和格式
                accept:接受上传的文件类型（thumbnail-mode 模式下此参数无效） string
           -->
          <el-upload
            class="avatar-uploader"
            :action="`${this.baseUrl}/admin/product/fileUpload`"
            list-type="picture-card"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            accept="image/jpeg,image/png"
          >
            <img
              v-if="trademark.logoUrl"
              :src="trademark.logoUrl"
              class="avatar upload-logoImg"
            />
            <i class="el-icon-plus avatar-uploader-icon" v-else> </i>
            <div class="el-upload__tip" slot="tip" v-show="!trademark.logoUrl">
              只能上传jpeg/jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdTrademark">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  reqGetTrademarkList,
  reqAddTrademark,
  reqDeleteTrademark,
  reqUpdateTrademark,
} from "@/api/production/trademark";
export default {
  name: "Trademark",
  data() {
    return {
      currentPage: 1,
      pageSize: 3,
      total: 100,
      visible: false,
      loading: false,
      trademarkList: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      trademark: {
        tmName: "",
        logoUrl: "",
      },
      rules: {
        tmName: [
          { required: true, message: "请输入品牌名称", trigger: "blur" },
        ],
        logoUrl: [
          { required: true, message: "请上传品牌LOGO", trigger: "change" },
        ],
      },
      isAddOrUpdate: false,
    };
  },
  mounted() {
    this.search();
  },
  methods: {
    handleSizeChange(val) {
      this.pageSize = val;
      this.search();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.search();
    },
    //图片上传成功
    handleAvatarSuccess(file) {
      this.trademark.logoUrl = file.data;
      // 修改照片
      // 清空图片表单校验结果
      this.$refs.form?.clearValidate(["logoUrl"]);
    },
    // 图片提交之前
    beforeAvatarUpload(file) {
      let imgType = ["image/jpeg", "image/png", "image/jpg"];
      const isQualify = imgType.indexOf(file.type) !== -1;
      const isLt = file.size / 1024 < 500;

      if (!isQualify) {
        this.$message.error("上传头像图片只能是 JPG,PNG,JPG 格式!");
      }
      if (!isLt) {
        this.$message.error("上传头像图片大小不能超过 500KB!");
      }
      return isQualify && isLt;
    },
    // 显示dialog如果有值的话清空dialog
    showDialog() {
      // 清空内容,dom更新是异步的，第一次添加时没有数据，不需要重置
      // ？是es11的新语法，判断当前的form是否有值
      //判断是否是添加修改，如果是添加这清空，如果是修改这显示改行数据 true是修改
      // 这个是指清空表单校验
      this.$refs.form?.resetFields();
      // 清空数据
      this.trademark = {
        tmName: "",
        logoUrl: "",
      };
      this.visible = true;
    },
    // 修改trademark,弹窗的内容不清空
    updateTrademark(row) {
      // 修改数据
      this.isAddOrUpdate = true;
      this.visible = true;
      // 直接写row,直接指向同一个对象，响应式原理造成直接修改接收的row和this.trademark是同一个对象
      // 修改一个值页面就会变，只有重新赋值一个新对象则不会是响应的值，定义响应式数据，是一开始的时候数据就
      this.trademark = { ...row };
    },
    // 获取trademarkList
    async search() {
      this.loading = true;
      let res = await reqGetTrademarkList(this.currentPage, this.pageSize);
      // console.log(res);
      this.loading = false;
      this.trademarkList = res.records;
      this.total = res.total;
    },
    // 添加/修改品牌
    async addOrUpdTrademark() {
      // 再添加之前要整体在校验一次
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          //  表单校验成功了，判断是添加还是修改
          let { logoUrl, tmName, id } = this.trademark;
          let oldTrademark,
            isoldVal = true;
          const { isAddOrUpdate, trademarkList } = this;
          if (isAddOrUpdate) {
            ///修改，判断一下修改的值和之前的值是否一致
            oldTrademark = trademarkList.find((item) => {
              item.id === id;
              console.log(oldTrademark, 0);
            });
            // 判断二个对象的内容是否一致
            for (let key in oldTrademark) {
              if (oldTrademark[key] !== this.trademark[key]) {
                isoldVal = false;
              }
            }
            if (!isoldVal) reqUpdateTrademark(this.trademark);
            if (isoldVal) {
              this.visible = false;
              return;
            }
          } else {
            // 添加
            await reqAddTrademark(logoUrl, tmName);
          }
          // 提示一下添加成功
          this.$message({
            type: "success",
            message: `${isAddOrUpdate ? "修改" : "添加"}品牌成功~`,
          });
          // 刷新页面
          // location.reload();
          this.search();
          // 是弹框消失
          this.visible = false;
        }
      });
    },
    // 删除品牌
    delTrademark(row) {
      // console.log(row);
      this.$confirm(
        `此操作将永久<span style="color:red">${row.tmName}</span> 品牌名称, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          dangerouslyUseHTMLString: true, //使用html
        }
      ).then(() => {
        reqDeleteTrademark(row.id);
        //  更新页面，如果在当前页的数据只有一条则要改变当前页重新获取页数
        if (this.trademarkList.length === 1 && this.currentPage > 1) {
          this.currentPage--;
        }
        // 更新页面
        this.search();
        this.$message({
          type: "success",
          message: "删除成功!",
        });
      });
    },
  },
};
</script>

<style lang='sass' scoped>
.logoImg
  width: 100px
  height: 100px
.upload-logoImg
  width: 100%
  height: 100%
.card
  margin:10px
</style>